#!/bin/bash
# AI命令安装脚本 - Linux/Mac版本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 打印函数
print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查Python环境
check_python() {
    print_info "检查Python环境..."

    if command -v python3 &> /dev/null; then
        PYTHON_CMD="python3"
    elif command -v python &> /dev/null; then
        PYTHON_CMD="python"
    else
        print_error "未找到Python环境，请先安装Python 3.7+"
        exit 1
    fi

    PYTHON_VERSION=$($PYTHON_CMD --version 2>&1 | awk '{print $2}')
    print_info "Python版本: $PYTHON_VERSION"
}

# 检查依赖
check_dependencies() {
    print_info "检查系统依赖..."

    # 检查Git
    if ! command -v git &> /dev/null; then
        print_error "未找到Git，请先安装Git"
        exit 1
    fi
    print_info "Git版本: $(git --version)"

    # 检查curl（用于下载）
    if ! command -v curl &> /dev/null; then
        print_warn "未找到curl，将使用Python的urllib进行下载"
    else
        print_info "Curl版本: $(curl --version | head -1)"
    fi
}

# 创建必要的目录
create_directories() {
    print_info "创建必要的目录..."

    local directories=(
        ".ai/commands"
        ".ai/scripts"
        ".ai/prompts/basic"
        ".ai/prompts/professional"
        ".ai/prompts/creative"
        ".ai/prompts/workflow"
        ".ai/docs"
        "logs"
        "temp"
    )

    for dir in "${directories[@]}"; do
        if [ ! -d "$dir" ]; then
            mkdir -p "$dir"
            print_info "创建目录: $dir"
        fi
    done
}

# 安装AI命令
install_commands() {
    print_info "安装AI命令..."

    # 检查是否存在ai-code-ext.py
    if [ ! -f "ai-code-ext.py" ]; then
        print_error "未找到ai-code-ext.py文件"
        exit 1
    fi

    # 执行安装
    $PYTHON_CMD ai-code-ext.py install

    if [ $? -eq 0 ]; then
        print_info "AI命令安装成功"
    else
        print_error "AI命令安装失败"
        exit 1
    fi
}

# 设置权限
setup_permissions() {
    print_info "设置文件权限..."

    # 设置脚本执行权限
    chmod +x .ai/scripts/*.sh 2>/dev/null || true

    # 设置适当的文件权限
    find .ai -type f -name "*.md" -exec chmod 644 {} \;
    find .ai -type f -name "*.py" -exec chmod 644 {} \;
    find .ai -type f -name "*.json" -exec chmod 644 {} \;

    print_info "权限设置完成"
}

# 创建配置文件
create_config() {
    print_info "创建配置文件..."

    local config_file=".ai/config.json"
    if [ ! -f "$config_file" ]; then
        cat > "$config_file" << 'EOF'
{
  "version": "1.0.0",
  "installed_at": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "auto_update": true,
  "log_level": "info",
  "cache_enabled": true,
  "prompts_enabled": true,
  "default_language": "zh-CN"
}
EOF
        print_info "创建配置文件: $config_file"
    else
        print_info "配置文件已存在: $config_file"
    fi
}

# 验证安装
verify_installation() {
    print_info "验证安装..."

    local errors=0

    # 检查必要目录
    local required_dirs=(".ai/commands" ".ai/prompts" ".ai/scripts" ".ai/docs")
    for dir in "${required_dirs[@]}"; do
        if [ ! -d "$dir" ]; then
            print_error "缺少目录: $dir"
            ((errors++))
        else
            file_count=$(find "$dir" -type f | wc -l)
            print_info "$dir 目录: $file_count 个文件"
        fi
    done

    # 检查核心文件
    local required_files=(
        ".ai/commands/analyze.md"
        ".ai/commands/plan.md"
        ".ai/commands/specify.md"
        ".ai/prompts/README.md"
        ".ai/scripts/install.sh"
    )

    for file in "${required_files[@]}"; do
        if [ ! -f "$file" ]; then
            print_error "缺少文件: $file"
            ((errors++))
        else
            print_info "找到文件: $file"
        fi
    done

    if [ $errors -eq 0 ]; then
        print_info "安装验证通过"
        return 0
    else
        print_error "安装验证失败，发现 $errors 个问题"
        return 1
    fi
}

# 显示使用说明
show_usage() {
    print_info "安装完成！使用说明："
    echo ""
    echo "1. 查看已安装目录："
    echo "   python ai-code-ext.py list"
    echo ""
    echo "2. 使用AI命令："
    echo "   # 从.ai/commands目录选择合适的命令文件"
    echo "   # 复制内容到AI工具中使用"
    echo ""
    echo "3. 使用提示词库："
    echo "   # 从.ai/prompts目录选择合适的提示词"
    echo "   # 根据需要进行个性化调整"
    echo ""
    echo "4. 同步更新："
    echo "   python ai-code-ext.py sync"
    echo ""
    echo "5. 查看缓存状态："
    echo "   python ai-code-ext.py cache status"
    echo ""
    echo "更多信息请查看 .ai/docs/README.md"
}

# 主函数
main() {
    echo "========================================"
    echo "AI命令安装器 - 自动安装脚本"
    echo "========================================"
    echo ""

    print_info "开始安装AI命令..."

    check_python
    check_dependencies
    create_directories
    install_commands
    setup_permissions
    create_config

    if verify_installation; then
        echo ""
        echo "========================================"
        print_info "安装成功完成！"
        echo "========================================"
        show_usage
    else
        echo ""
        echo "========================================"
        print_error "安装过程中出现问题，请检查错误信息"
        echo "========================================"
        exit 1
    fi
}

# 执行主函数
main "$@"